package com.yqg.education.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yqg.education.common.Result;
import com.yqg.education.controller.dto.ReceiveAnnounceDto;
import com.yqg.education.entity.ClassStudent;
import com.yqg.education.entity.ReceiveAnnounce;
import com.yqg.education.entity.SendAnnounce;
import com.yqg.education.entity.TrainClass;
import com.yqg.education.mapper.ReceiveAnnounceMapper;
import com.yqg.education.service.IClassStudentService;
import com.yqg.education.service.IReceiveAnnounceService;
import com.yqg.education.service.ISendAnnounceService;
import com.yqg.education.service.ITrainClassService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * ReceiveAnnounceController 前端控制器
 * @author 张芸博
 * @since 2025-04-10
 */
@RestController
@RequestMapping("/receive-announce")
public class ReceiveAnnounceController {

    @Resource
    private IReceiveAnnounceService receiveAnnounceService;
    @Resource
    private ReceiveAnnounceMapper receiveAnnounceMapper;

    @Resource
    private IClassStudentService classStudentService;
    @Resource
    private ITrainClassService trainClassService;

    @Resource
    private ISendAnnounceService sendAnnounceService;
    /**
    *  新增或者更新
    */
    @PostMapping("/edit")
    public Result save(@RequestBody ReceiveAnnounce receiveAnnounce) {
        return Result.success(receiveAnnounceService.saveOrUpdate(receiveAnnounce));
    }

    @PostMapping("/editAll")
    @Transactional(rollbackFor = Exception.class)
    public Result editAll(@RequestBody ReceiveAnnounceDto receiveAnnounceDto) {
        Set<Long> userIds = new HashSet<>();
        if (receiveAnnounceDto.getClassIds() != null && receiveAnnounceDto.getClassIds().size() > 0) {
            LambdaQueryWrapper<ClassStudent> classStudentQueryWrapper = new LambdaQueryWrapper<>();
            classStudentQueryWrapper.in(ClassStudent::getClassId, receiveAnnounceDto.getClassIds());
            userIds.addAll(classStudentService.list(classStudentQueryWrapper).stream().map(ClassStudent::getStuId).collect(Collectors.toSet()));
            LambdaQueryWrapper<TrainClass> trainClassQueryWrapper = new LambdaQueryWrapper<>();
            trainClassQueryWrapper.in(TrainClass::getId, receiveAnnounceDto.getClassIds());
            userIds.addAll(trainClassService.list(trainClassQueryWrapper).stream().map(TrainClass::getManageId).collect(Collectors.toSet()));
        }
        if (receiveAnnounceDto.getUserIds() != null && receiveAnnounceDto.getUserIds().size() > 0) {
            userIds.addAll(receiveAnnounceDto.getUserIds());
        }
        if (userIds.size() > 0) {
            ArrayList<ReceiveAnnounce> receiveAnnounces = new ArrayList<>();
            for (Long userId:userIds) {
                ReceiveAnnounce receiveAnnounce = new ReceiveAnnounce();
                receiveAnnounce.setReceiveId(userId);
                receiveAnnounce.setSendAnnounceId(receiveAnnounceDto.getSendAnnounceId());
                receiveAnnounce.setState("0");
                receiveAnnounce.setCreateTime(LocalDateTime.now());
                receiveAnnounce.setIsDelete(0);
                receiveAnnounces.add(receiveAnnounce);
            }
            receiveAnnounceService.saveOrUpdateBatch(receiveAnnounces);
        }
        SendAnnounce sendAnnounce = sendAnnounceService.getById(receiveAnnounceDto.getSendAnnounceId());
        sendAnnounce.setIsSend(1);
        sendAnnounce.setSendTime(LocalDateTime.now());
        sendAnnounceService.saveOrUpdate(sendAnnounce);
        return Result.success();
    }

    @GetMapping("/updateState/{id}")
    public Result updateState(@PathVariable Integer id) {
        ReceiveAnnounce receiveAnnounce =receiveAnnounceService.getById(id);
        receiveAnnounce.setState("1");
        return Result.success(receiveAnnounceService.saveOrUpdate(receiveAnnounce));
    }

    /**
    *  删除
    */
    @GetMapping("delete/{id}")
    public Result delete(@PathVariable Integer id) {
        ReceiveAnnounce receiveAnnounce =receiveAnnounceService.getById(id);
        return Result.success(receiveAnnounceService.saveOrUpdate(receiveAnnounce));
    }
    /**
    *  查询所有
    */
    @GetMapping("/all")
    public Result findAll() {
        QueryWrapper<ReceiveAnnounce> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", "0");
       List<ReceiveAnnounce> list=  receiveAnnounceService.list(queryWrapper);
        return Result.success(list);
    }
    /**
    *  根据id查询
    */
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(receiveAnnounceService.getById(id));
    }
    /**
    *  分页查询
    */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
    String title,
        Integer userId) {
        pageNum = pageNum * pageSize - pageSize;
        List<ReceiveAnnounce> receiveAnnounces = receiveAnnounceMapper.pageList(pageNum, pageSize,title,  userId);
        Long count = receiveAnnounceMapper.findCount(title,userId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("records", receiveAnnounces);
        map.put("total", count);
        return Result.success(map);
    }

    /**
     * 学员端获取通知信息接口
     */
    @GetMapping("/stuFindReceiveAnnouncePage")
    public Result stuFindReceiveAnnouncePage(@RequestParam Integer pageNum,
                                             @RequestParam Integer pageSize,
                                             @RequestParam(required = false) String name,
                                             @RequestParam Integer userId) {
        return Result.success(receiveAnnounceService.findReceiveAnnouncePage(pageNum, pageSize, name, userId));
    }
    /**
     * APP端修改通知已读状态
     */
    @GetMapping("/stuUpdateReceiveAnnounceState")
    public Result stuUpdateReceiveAnnounceState(@RequestParam(required = false) List<Long> ids,
                                                @RequestParam(required = false) Long id){
        LambdaQueryWrapper<ReceiveAnnounce> receiveAnnounceLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ReceiveAnnounce receiveAnnounce = new ReceiveAnnounce();
        receiveAnnounce.setState("1");
        if (ids != null) {
            // 批量修改状态
            receiveAnnounceLambdaQueryWrapper.in(ReceiveAnnounce::getId,ids);
            receiveAnnounceService.update(receiveAnnounce,receiveAnnounceLambdaQueryWrapper);
        } else if (id != null) {
            //单独修改状态
            receiveAnnounceLambdaQueryWrapper.eq(ReceiveAnnounce::getId, id);
            receiveAnnounceService.update(receiveAnnounce, receiveAnnounceLambdaQueryWrapper);
        }else{
            return Result.error();
        }
        return Result.success();
    }

    /**
     * APP端获取未读通知信息数量
     */
    @GetMapping("/getNoReadMsgCount")
    public Result getNoReadMsgCount(@RequestParam Integer userId) {
        LambdaQueryWrapper<ReceiveAnnounce> receiveAnnounceQueryWrapper = new LambdaQueryWrapper<>();
        receiveAnnounceQueryWrapper.eq(ReceiveAnnounce::getIsDelete, 0);
        receiveAnnounceQueryWrapper.eq(ReceiveAnnounce::getReceiveId, userId);
        receiveAnnounceQueryWrapper.eq(ReceiveAnnounce::getState, "0");
        return Result.success(receiveAnnounceService.count(receiveAnnounceQueryWrapper));
    }

    @GetMapping("/getRecAnnounceById")
    public Result getRecAnnounceById(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           Long announceId) {
        pageNum = pageNum * pageSize - pageSize;
        List<ReceiveAnnounce> receiveAnnounces = receiveAnnounceMapper.getRecAnnouncePage(pageNum, pageSize,announceId);
        Long count = receiveAnnounceMapper.getRecAnnounceCount(announceId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("records", receiveAnnounces);
        map.put("total", count);
        return Result.success(map);
    }
}

